package com.lw.leetcode.arr.b;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * b
 * arr
 * 2491. 划分技能点相等的团队
 *
 * @author liw
 * @version 1.0
 * @date 2022/12/4 12:20
 */
public class DividePlayers {

    public static void main(String[] args) {
        DividePlayers test = new DividePlayers();

        // 22
        int[] arr = {3, 2, 5, 1, 3, 4};

        long l = test.dividePlayers(arr);
        System.out.println(l);
    }

    public long dividePlayers(int[] skill) {
        Map<Integer, Integer> map = new HashMap<>();
        int sum = 0;
        for (int i : skill) {
            sum += i;
            map.merge(i, 1, (a, b) -> a + b);
        }
        int length = skill.length >> 1;
        if (sum % length != 0) {
            return -1;
        }
        int t = sum / length;
        long all = 0;
        for (int a : skill) {
            Integer c = map.get(a);
            if (c == 0) {
                continue;
            }
            map.put(a, c - 1);
            c = map.get(t - a);
            if (c == null || c == 0) {
                return -1;
            }
            map.put(t - a, c - 1);
            all += (t - a) * a;
        }
        return all;
    }

}
